package cn.gzmli.dtt.common.service.log;

import cn.gzmli.dtt.common.entity.User;
import cn.gzmli.dtt.common.entity.LoginLog;
import cn.gzmli.dtt.common.utils.BaseService;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * @Descript
 * @Author xsx
 * @Date 2018/3/21
 */
@Service
@Transactional
public class LoginLogService extends BaseService<LoginLog> {
    /**
     * 保存登录日志
     * @param sessionId
     * @param user
     * @throws Exception
     */
    public void saveLoginLog(String sessionId, User user) throws Exception {
        final String query = "SELECT * FROM login_log WHERE sessionId=? AND type=1";
        Map<String, Object> data;
        try {
            data = this.getDao().getJdbcTemplate().queryForMap(query, sessionId);
        }catch (EmptyResultDataAccessException e){
            data = null;
        }
        if (data==null){
            final String insert = "INSERT INTO login_log(name,sessionId,userId,loginName,userName,type,orgId) VALUES(?,?,?,?,?,?,?)";
            this.getDao().getJdbcTemplate().update(insert, "系统登录", sessionId, user.getId(), user.getUserName(), user.getName(), 1,user.getDepartment().getId());
        }
    }

    /**
     * 保存注销日志
     * @param sessionId
     * @param user
     * @throws Exception
     */
    public void saveLogout(String sessionId, User user){
        final String query = "SELECT * FROM login_log WHERE sessionId=? AND type=2";
        Map<String, Object> data;
        try {
            data = this.getDao().getJdbcTemplate().queryForMap(query, sessionId);
        }catch (EmptyResultDataAccessException e){
            data = null;
        }catch (IncorrectResultSizeDataAccessException e){
            e.printStackTrace();
            data = null;
        }
        if (data==null){
            if (user!=null){
                final String insert = "INSERT INTO login_log(name,sessionId,userId,loginName,userName,type,orgId) VALUES(?,?,?,?,?,?,?)";
                this.getDao().getJdbcTemplate().update(insert, "系统注销", sessionId, user.getId(), user.getUserName(), user.getName(), 2,user.getDepartment().getId());
            }
        }else{
            final String update = "UPDATE login_log SET createTime=? WHERE id=?";
            this.getDao().getJdbcTemplate().update(update, new Date(), data.get("id"));
        }
    }
}
